/**
 * 
 */
package pl.com.like.sequoia.biojava.util.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.zip.GZIPInputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import pl.com.like.sequoia.biojava.util.IFileHelper;
import pl.com.like.sequoia.exceptions.LogicalException;

/**
 * @author Pawel Wolanski
 * 
 */
public class FileHelper implements IFileHelper {

	private static IFileHelper instance = null;

	private final static Logger log = LoggerFactory.getLogger(FileHelper.class);

	public static IFileHelper getInstance() {
		if (instance == null) {
			instance = new FileHelper();
		}
		return instance;
	}

	private FileHelper() {

	}

	/** {@inheritDoc} */
	public InputStream getInputStream(File inputFile) throws LogicalException {
		Assert.notNull(inputFile);
		InputStream input = null;
		InputStream defaultInput = null;
		try {
			defaultInput = new FileInputStream(inputFile);
			GZIPInputStream inputGz = new GZIPInputStream(defaultInput);
			input = inputGz;
		} catch (FileNotFoundException e) {
			String msg = MessageFormat.format("file {0} doesn't exists on server. Stream set as null", inputFile
					.getAbsolutePath());
			log.info(msg, e);
			input = null;
			throw new LogicalException(msg, e);
		} catch (IOException e) {
			log.info(MessageFormat.format("opened stream is not gzipped {0}", inputFile.getAbsolutePath()));
			input = defaultInput;
		}
		return input;
	}

	/** {@inheritDoc} */
	public InputStream getInputStream(URL url) throws LogicalException {
		InputStream input = null;
		InputStream defaultInput = null;
		try {
			defaultInput = url.openStream();
			GZIPInputStream inputGz = new GZIPInputStream(defaultInput);
			input = inputGz;
		} catch (FileNotFoundException e) {
			String msg = MessageFormat.format("file {0} doesn't exists on server. Stream set as null", url
					.toExternalForm());
			log.info(msg, e);
			input = null;
			throw new LogicalException(msg, e);
		} catch (IOException e) {
			log.info(MessageFormat.format("opened stream is not gzipped {0}", url.toExternalForm()));
			input = defaultInput;
		}
		return input;
	}

}
